var DBFactory = require('../db/mysql');
var async = require('async');
var PostHelper = require('./../util/postHelper');
var backTaskDao = module.exports;

backTaskDao.get_news = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
            if (error) {
                cb(error);
            } else {
                async.waterfall([
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },
                    function (callback) {
                        for (let i = 1; i < 20; i++) {
                            PostHelper.baseRequestByGet('https://cnodejs.org/api/v1/topics', {
                                page: i,
                                tab: 'good'
                            }, function (err, result) {
                                if (err) {
                                    console.log(err);
                                } else {
                                    if (result.success && result.success == true) {
                                        if (result.data.length > 0) {
                                            result.data.forEach(data => {
                                                backTaskDao.checkArticleExists(data, function (err, result) {
                                                    if (err) {
                                                        console.log(err);
                                                    } else {
                                                        if (result.status == 200) {
                                                            console.log(result);
                                                        } else {
                                                            console.log(result);
                                                        }
                                                    }
                                                });
                                            });
                                        } else {
                                            console.log('文章已查询结束!');
                                        }
                                    } else {
                                        console.log('进程执行出现异常!');
                                    }
                                }
                            });
                        }

                        callback(null, true, {
                            status: 200,
                            msg: '保存文章数据成功!'
                        });
                    },
                ], function (DbErr, isSuccess, uidOrInfo) {
                    if (DbErr) {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, DbErr);
                            }
                        });
                    } else if (!isSuccess) {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, DbErr);
                            }
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, uidOrInfo);
                            }
                        });
                    }
                });
            }
        });
    }
}

backTaskDao.checkArticleExists = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) { //使用transaction进行转账
            if (error) {
                cb(error);
            } else {
                async.waterfall([
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },
                    function (callback) {
                        var sql = 'select count(*) as count from article where uniquekey = ?';
                        var value = [data.id];
                        connection.query(sql, value, function (err, result) {
                            if (err) {
                                data.is_exist = 0;
                            } else {
                                if (result[0].count == 0) {
                                    console.log('文章id：' + data.id + '已存在!');
                                    data.is_exist = 1;
                                } else {
                                    data.is_exist = 0;
                                }
                            }

                            callback(null, data);
                        });
                    },
                    function (data, callback) {
                        if (data.is_exist == 1) {
                            var sql = 'insert into article set ?';
                            var value = {
                                title: data.title,
                                content: data.content,
                                gist: data.title,
                                labels: '分享',
                                created_date: new Date(),
                                status: 1,
                                author: data.author.loginname,
                                openid: 'oTqjy5G2r6OI09OJfvIkekC9FbIc',
                                app_sid: 'nyl',
                                read_count: data.visit_count,
                                uniquekey: data.id,
                                url: '',
                                main_pic: 'http://pic.niyueling.cn/upload_avatar/2019/11/11/0/0/163054893.jpg',
                                avatar: 'https://wx.qlogo.cn/mmopen/vi_32/DBnxwgYFBh2rBzuerfaOyD1XAwjL1vV9SQuVPVDT5DHZJ1NujBjJL1GABPgrhNOedtYnTictJBMKIqnt5pvZSfg/132'
                            };
                            connection.query(sql, value, function (err, result) {
                                if (err) {
                                    console.log(err);
                                } else {
                                    if (result.affectedRows == 0) {
                                        console.log('文章保存出现异常!');
                                    } else {
                                        console.log('文章保存成功!');
                                    }
                                }
                            });
                        }

                        callback(null, true, {
                            status: 200,
                            msg: '进程执行成功!'
                        });
                    }
                ], function (DbErr, isSuccess, uidOrInfo) {
                    if (DbErr) {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, DbErr);
                            }
                        });
                    } else if (!isSuccess) {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, DbErr);
                            }
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, uidOrInfo);
                            }
                        });
                    }
                });
            }
        });
    }
}